const fs = require('fs')
const path = require('path')
const process = require('process')
const fsExtra = require('fs-extra')
const commander = require('commander')
const { cloneAll } = require('./cloneAll')
const { readFileByLine } = require('./readLine')
const { writeResult } = require('./writeResult')
const { logCyan, logRed, logBlue, logGreen } = require('./utils')

commander.arguments('<name>', 'json文件名').parse(process.argv)

let dataFileName = commander.args[0] || ''
if (!dataFileName) {
	logRed(`请先在data文件夹中创建配置文件`)
	process.exit()
}

let configObj = {}
let gitUrl = []
let targetPath = '../YMM'
let targetString = []
let targetStringInfo = []



async function findAll() {
	await cloneAll(targetPath, gitUrl)

	let catalog = fs.readdirSync(targetPath)
	catalog = catalog.map((item) => (item = `${targetPath}/${item}`))
	logCyan(`【clone完毕】===> ${catalog}`)

	for (const val of catalog) {
		await startFind(val)
	}

}

async function startFind(filePath) {
	if (!fs.existsSync(filePath)) {
		logRed(`【${filePath}】文件目录不存在！`)
		return
	}
	if (fs.existsSync(filePath)) {
		if (isFile(filePath)) {
			// 按文件查找
			// checkString(filePath)
			// 按行查找
			const result = await readFileByLine(filePath, targetString)
			// 分文件夹打印日志
			if (result.length) {
				writeLog(filePath, result)
				// saveResult(result)
			}
		}
		if (isDirectory(filePath)) {
			let files = fs.readdirSync(filePath)
			for (const val of files) {
				let temp = path.join(filePath, val)
				if (temp.indexOf('src') > -1) {
					if (isDirectory(temp)) await startFind(temp)
					// 按文件查找，返回文件目录
					// if (isFile(temp)) checkString(temp)
					// 按行查找，返回文件目录、行
					if (isFile(temp)) {
						const result = await readFileByLine(temp, targetString)
						if (result.length) {
							writeLog(filePath, result)
							//   saveResult(result)
						}
					}
				}
			}
		}
	}
}

function isFile(filePath) {
	return fs.statSync(filePath).isFile()
}

function isDirectory(filePath) {
	return fs.statSync(filePath).isDirectory()
}

function checkString(fileName) {
	let data = readFile(fileName)
	let exc = new RegExp(targetString)
	if (exc.test(data)) logBlue(`找到目标文字啦，文件目录是==》【${fileName}】`)
}

function readFile(fileName) {
	return fs.readFileSync(fileName, 'utf-8')
}

function saveResult(result) {
	// targetStringInfo = [...targetStringInfo, ...result]
}

async function readConfig() {
	if (fs.existsSync(`../data/${dataFileName}.json`)) {
		configObj = fsExtra.readJSONSync(`../data/${dataFileName}.json`)
		targetString = configObj.targetString || ''
		gitUrl = configObj.gitUrl || []
		if (!targetString || !gitUrl.length) {
			logRed(`${dataFileName}.json文件中缺少配置！`)
			process.exit()
		}
		if (fs.existsSync(targetPath)) {
			fsExtra.removeSync(targetPath)
		}
		fsExtra.ensureDirSync(targetPath)
		await findAll()
	} else {
		logRed(`data文件夹下找不到${dataFileName}.json文件！`)
		process.exit()
	}
}

function writeLog(path, result) {
	let name = path.split('/')[2]

	for (const item of targetStringInfo) {
		if (item.key == name) {
			item.value = [...item.value, ...result]
		}
		if (item.key != name) {
			targetStringInfo.push({ key: name, value: result })
		}
	}
	if (!targetStringInfo.length) {
		targetStringInfo.push({ key: name, value: result })
	}
	let currentContent = targetStringInfo
		.filter((item) => item.key == name)
		.map((item) => item.value)[0]

	currentContent = [...new Set(currentContent)]

	const totalContent = `项目名:${name}\n查找到关键字的总数:${
		currentContent.length || 0
	}个`

	let targetKeyObj = {}

	targetString.map((key) => {
		currentContent.map((item) => {
			if (key == item.target) {
				if (targetKeyObj[key]) {
					targetKeyObj[key] = [...targetKeyObj[key], item]
				} else {
					targetKeyObj[key] = [item]
				}
			}
		})
	})

	const targetKeyContent = Object.keys(targetKeyObj).map((item) => {
		return `\n关键字【${item}】共: ${targetKeyObj[item].length}个`
	})

	fsExtra.ensureDirSync(`../YMM/log/${name}`)
	fsExtra.outputFile(
		`../YMM/log/${name}/detail.json`,
		JSON.stringify(currentContent)
	)

	fsExtra.outputFile(
		`../YMM/log/${name}/stat.txt`,
		`${totalContent}${targetKeyContent.toString()}`
	)
}

module.exports = {
	readConfig,
}
